use std::thread;
use std::time::Duration;
use opencv::{core, highgui, imgproc, prelude::*, videoio, objdetect, types, Result};
// 读取、显示摄像头视频
pub fn run() -> Result<()>{
    let window = "video capture";
	// 打开默认窗口
	highgui::named_window_def(window).unwrap();
     
    let (xml, mut cam) = {
		(
			core::find_file_def("haarcascades/haarcascade_frontalface_alt.xml")?, // 人脸跟踪配置文件
			videoio::VideoCapture::new(0, videoio::CAP_ANY)?, // 0 is the default camera
		)
	};
    // 判断相机是否打开
	if videoio::VideoCapture::is_opened(&cam).unwrap() {
		eprintln!("摄像机已打开！");
	}

    let mut face = objdetect::CascadeClassifier::new(&xml)?;

	loop {
		let mut frame = Mat::default();		// 一个 n 维密集数字单通道或多通道数组
		// 捕获帧
		if let Err(_e) = cam.read(&mut frame) {
			break;
		}

        if frame.size()?.width == 0 {
			thread::sleep(Duration::from_secs(50));
			continue;
		}

        let mut gray = Mat::default();
		imgproc::cvt_color_def(&frame, &mut gray, imgproc::COLOR_BGR2GRAY)?;
        
        let mut reduced = Mat::default();
		imgproc::resize(
			&gray,
			&mut reduced,
			core::Size { width: 0, height: 0 },
			0.25f64,
			0.25f64,
			imgproc::INTER_LINEAR,
		)?;

        let mut faces = types::VectorOfRect::new();
		face.detect_multi_scale(
			&reduced,
			&mut faces,
			1.1,
			2,
			objdetect::CASCADE_SCALE_IMAGE,
			core::Size { width: 30, height: 30 },
			core::Size { width: 0, height: 0 },
		)?;
		
		for face in faces {
			let scaled_face = core::Rect::new(face.x * 4, face.y * 4, face.width * 4, face.height * 4);
			imgproc::rectangle_def(&mut frame, scaled_face, (0, 255, 0).into())?;
		}
		
        highgui::imshow(window, &frame)?;
		// 等待用户按键，监听键盘动作
		if let Ok(key) = highgui::wait_key(10){
			if key > 0 {
				highgui::destroy_all_windows()?;
				cam.release()?;
				break;
			}
		}
	}
    Ok(())
}